<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查询相关的方法</title>
</head>
<body>
<script>
    onload = function () {
        // 当页面加完成时执行
        let elementsByTagName = document.getElementsByTagName("p");
        // 获取所有标签为p的集合
        for (let i = 0; i < elementsByTagName.length; i++) {
            elementsByTagName[i].innerHTML = i;
        }
        let elementsByName = document.getElementsByName("hello")[0];
        elementsByName.value = "hello";
        // 设置value为hello
        elementsByName.name = "hi";
        // 设置name为hi
        // alert("标签类型"+elementsByName.type+" 标签name "+elementsByName.name+" 标签value "+elementsByName.value)
        // alert("父标签是 "+elementsByName.parentNode);
        let elementById = document.getElementById('fatherDiv');
        let children = elementById.childNodes;
        for (let i = 0; i < children.length; i++) {
            // alert(i+","+children[i]);
        }
        message = "";
        // 记录获取的标签
        traverseAllNodes(document);
        // 获取所有标签
        let elementById1 = document.getElementById("finalDiv");
        // 获取要写入的div的id
        elementById1.style.fontSize = '20px';
        elementById1.style.color = 'red';
        elementById1.innerHTML = message;
        // 把获取的所有标签写入div

    }

    function traverseAllNodes(node) {
        // TODO 遍历所有节点，结果存储在message中
        let nodeName = node.nodeName;
        let nodeType = node.nodeType;
        let nodeValue = node.nodeValue;
        message += `节点名:${nodeName} 节点类型:${nodeType} 节点值: ${nodeValue} <br>`;
        // 把节点的信息放入message中;
        if (nodeType !== 1 && nodeType !== 9) {
            // 如果不是element或者document就跳出
            return;
        }
        if (nodeType === 1) {
            // 如果是element
            let attributes = node.attributes;
            // 获取所有的子element
            for (let i = 0; i < attributes.length; i++) {
                let name = attributes[i].name;
                let value = attributes[i].value;
                // 获取属性名和属性值
                message += `node.nodeName标签的属性: ${name} ${value} <br>`;
            }
        }
        let childNodes = node.childNodes;
        // 获取所有的子元素
        for (let i = 0; i < childNodes.length; i++) {
            // 递归遍历
            traverseAllNodes(childNodes[i]);
        }
    }
</script>
<p>hello</p>
<p>hi</p>
<p>ok</p>
<input type="button" name="hello" value="fasdfa">
<div id="fatherDiv">
    <div id="midDiv">
        <div id="sonDiv">hello</div>
    </div>
</div>
<div id="finalDiv"></div>
</body>
</html>